﻿using K9Nano.Updater.Utils;

namespace K9Nano.Updater.Pipes;

public class InstallPipe : UpdatePipeBase
{
    public InstallPipe()
    {
        PipeName = "安装";
    }

    protected override Task InvokeCoreAsync(UpdateContext context, CancellationToken cancellation)
    {
        var downloadPath = context.GetDownloadDirectory();
        if (!Directory.Exists(downloadPath))
        {
            context.Terminated = true;
            context.LogError("更新文件下载目录不存在: {path}", downloadPath);
            return Task.CompletedTask;
        }

        if (context.Package is null)
        {
            context.LogError("更新包元数据不存在");
            return Task.CompletedTask;
        }

        for (var i = 0; i < context.Package.Files.Count; i++)
        {
            var item = context.Package.Files[i];
            var sourceFile = PathUtils.CombineFileUri(downloadPath, item.FileUri);
            if (!File.Exists(sourceFile))
            {
                context.Terminated = true;
                context.LogError("更新文件下载目录中没有找到{file}", item.FileUri);
                return Task.CompletedTask;
            }

            var targetPath = PathUtils.CombineFileUri(context.WorkingDirectory, item.TargetPath);

            switch (item.Action)
            {
                case EInstallAction.CreateOrUpdate:
                    {
                        File.Copy(sourceFile, targetPath, true);
                    }
                    break;
                case EInstallAction.Delete:
                    {
                        File.Delete(targetPath);
                    }
                    break;
                case EInstallAction.Extract:
                    {
                        ZipUtils.ExtractToDirectory(sourceFile, targetPath);
                    }
                    break;
                default:
                    context.Terminated = true;
                    context.LogError("不支持的更新操作");
                    break;
            }

            context.ReportProgress(i + 1, context.Package.Files.Count);
        }
        return Task.CompletedTask;
    }
}
